<template>
    <div class="login">
        <el-row class="login_container">
            <el-col :span="16" class="login_container_left">
                <el-row
                    type="flex"
                    justify="center"
                    align="middle"
                    class="login-box"
                >
                    <!-- 手机号输入页面 -->
                    <transition name="slide-left" mode="out-in">
                        <el-card v-if="isInputMobile" key="inputMobile">
                            <template slot="header">
                                <span>登录飞书</span>
                            </template>

                            <el-tabs v-model="activeName">
                                <el-tab-pane label="手机号" name="first">
                                    <el-input
                                        :value="inputMobile"
                                        placeholder="请输入手机号"
                                        @input="handleMobileInputChange"
                                    >
                                        <template slot="prepend">
                                            +86
                                        </template>
                                    </el-input>

                                    <el-button
                                        type="primary"
                                        round
                                        @click="handleInputCode"
                                        >下一步</el-button
                                    >
                                </el-tab-pane>

                                <el-tab-pane label="邮箱" name="second"
                                    >配置管理</el-tab-pane
                                >
                            </el-tabs>
                        </el-card>

                        <el-card v-else key="inputCode">
                            <div slot="header">
                                <el-row>
                                    <el-link
                                        icon="el-icon-back"
                                        @click.prevent="goBack"
                                        >返回</el-link
                                    >
                                </el-row>

                                <el-row>
                                    <h3>验证手机号</h3>

                                    <p>
                                        请输入发送至 +86
                                        {{ inputMobile }} 的 6
                                        位验证码，有效期十分钟，如未收到，请尝试重新获取验证码。
                                    </p>
                                </el-row>
                            </div>

                            <el-row>
                                <el-input
                                    v-model="inputCode"
                                    placeholder="请输入6位验证码"
                                ></el-input>
                            </el-row>

                            <el-row>
                                <el-link
                                    type="primary"
                                    v-if="this.allowTime < 1"
                                    @click.prevent="handleInputCode"
                                    >重新获取验证码</el-link
                                >
                                <el-link disabled v-else
                                    >{{
                                        this.allowTime
                                    }}秒后可重新获取验证码</el-link
                                >
                            </el-row>

                            <el-row>
                                <el-button
                                    type="primary"
                                    @click="handleVerifyCode"
                                    >下一步</el-button
                                >
                            </el-row>
                        </el-card>
                    </transition>
                </el-row>
            </el-col>
            <el-col :span="8" class="login_container_right"> </el-col>
        </el-row>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeName: "first",
            isInputMobile: true,
            inputMobile: "",
            inputCode: "",
            allowTime: null,
            intervalId: 0,
        };
    },
    methods: {
        goBack() {
            this.isInputMobile = true;
            clearInterval(this.intervalId);
        },
        async handleInputCode() {
            const mobile = this.inputMobile.replace(/\D/g, "").substr(0, 11);

            // 发送验证码
            const res = await this.$http.get(`/code/${mobile}`);

            // 如果业务码响应 403，表示还不到 60 秒，不允许重复获取
            if (res.code === 403) {
                this.showTimer(Date.parse(res.data.create_time));
                return;
            }

            if (res.code === 404) {
                this.$notify.error({ title: "该手机号未注册" });
                return;
            }

            // 如果验证码发送失败
            if (res.code !== 200) {
                this.$notify.error({
                    title: "验证码发送失败",
                    message: res.message,
                });
                return;
            }

            // 验证码发送成功
            this.$notify.success({
                title: "验证码发送成功",
            });

            // 显示时间倒计时
            this.showTimer(Date.now() - 1000);
        },
        showTimer(startTime) {
            // 计算还剩多少秒可以重新获取验证码
            this.allowTime = Math.ceil((startTime + 60000 - Date.now()) / 1000);

            // 设置一个定时器，显示重新获取验证码倒计时
            this.intervalId = setInterval(() => {
                if (this.allowTime >= 0) {
                    this.allowTime -= 1;
                } else {
                    clearInterval(this.intervalId);
                }
            }, 1000);

            // 跳转到输入验证码页面
            this.isInputMobile = false;
        },
        /**
         * 手机号码格式化
         */
        handleMobileInputChange(val) {
            let value = val.replace(/\D/g, "").substring(0, 11);
            let valueLen = value.length;

            if (valueLen <= 3) {
                this.inputMobile = value;
            }

            if (valueLen > 3 && valueLen <= 8) {
                this.inputMobile = `${value.substr(0, 3)} ${value.substr(3)}`;
                return;
            }

            if (valueLen > 8) {
                this.inputMobile = `${value.substr(0, 3)} ${value.substr(
                    3,
                    4
                )} ${value.substr(7)}`;
            }
        },
        /**
         * 校验验证码输入的是否正确
         */
        async handleVerifyCode() {
            const mobile = this.inputMobile.replace(/\D/g, "").substr(0, 11);

            let res = await this.$http.post("/login", {
                mobile,
                code: this.inputCode,
            });

            if (res.code !== 200) {
                this.$notify.error({
                    title: "验证码校验错误",
                    message: res.message,
                });
                return;
            }

            // 登录成功，将信息保存到 sessionStorage 中
            const { token, menu, user } = res.data;
            window.sessionStorage.setItem("token", token);
            window.sessionStorage.setItem("menu", JSON.stringify(menu));
            window.sessionStorage.setItem("profile", JSON.stringify(user));
            // 到首页
            this.$router.push("/dashboard");
            window.sessionStorage.setItem("activeMenu", "/dashboard");
        },
    },
};
</script>

<style lang="less">
.login {
    height: 100%;

    &_container {
        height: 100%;

        &_left {
            height: 100%;
            background-color: #f2f6fc;

            .login-box {
                height: 100%;

                .el-card {
                    width: 450px;
                }
            }

            .el-input {
                margin-top: 10px;
            }

            .el-link {
                margin-top: 10px;
            }

            .el-button {
                width: 100%;
                margin-top: 15px;
            }
        }

        &_right {
            height: 100%;
            background-color: #e4e7ed;
        }
    }

    // DOM 正在离开
    .slide-left-leave-active,
    .slide-left-enter-active {
        position: absolute;
        transition: all 1s;
    }

    .slide-left-enter,
    .slide-left-leave-to {
        opacity: 0;
        transform: translateX(-100px);
    }

    .slide-left-enter-to,
    .slide-leave {
        opacity: 1;
    }
}
</style>
